<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="爬虫,">










<meta name="description" content="一、代理池介绍1、什么是代理 1代理服务器：fiddler  2、为什么使用代理就可以更改对应的ip呢 1本机的请求会先发送给代理服务器，代理服务器会接受本机发送过来的请求（当前请求对应的ip就是本机ip），然后代理服务器会将该请求进行转发，转发之后的请求对应的ip就是代理服务器的ip。  3、提供免费代理ip的平台 1234www.goubanjia.com快代理西祠代理代理精灵:http://">
<meta name="keywords" content="爬虫">
<meta property="og:type" content="article">
<meta property="og:title" content="爬虫UA代理">
<meta property="og:url" content="http://yoursite.com/2019/09/20/【爬虫02】1UA代理/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一、代理池介绍1、什么是代理 1代理服务器：fiddler  2、为什么使用代理就可以更改对应的ip呢 1本机的请求会先发送给代理服务器，代理服务器会接受本机发送过来的请求（当前请求对应的ip就是本机ip），然后代理服务器会将该请求进行转发，转发之后的请求对应的ip就是代理服务器的ip。  3、提供免费代理ip的平台 1234www.goubanjia.com快代理西祠代理代理精灵:http://">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-20T12:27:39.665Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="爬虫UA代理">
<meta name="twitter:description" content="一、代理池介绍1、什么是代理 1代理服务器：fiddler  2、为什么使用代理就可以更改对应的ip呢 1本机的请求会先发送给代理服务器，代理服务器会接受本机发送过来的请求（当前请求对应的ip就是本机ip），然后代理服务器会将该请求进行转发，转发之后的请求对应的ip就是代理服务器的ip。  3、提供免费代理ip的平台 1234www.goubanjia.com快代理西祠代理代理精灵:http://">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/20/【爬虫02】1UA代理/">





  <title>爬虫UA代理 | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/20/【爬虫02】1UA代理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">爬虫UA代理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-20T20:44:46+08:00">
                2019-09-20
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/爬虫/" itemprop="url" rel="index">
                    <span itemprop="name">爬虫</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/20/【爬虫02】1UA代理/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/20/【爬虫02】1UA代理/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一、代理池介绍"><a href="#一、代理池介绍" class="headerlink" title="一、代理池介绍"></a>一、代理池介绍</h2><p>1、什么是代理</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">代理服务器：fiddler</span><br></pre></td></tr></table></figure>

<p>2、为什么使用代理就可以更改对应的ip呢</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">本机的请求会先发送给代理服务器，代理服务器会接受本机发送过来的请求（当前请求对应的ip就是本机ip），然后代理服务器会将该请求进行转发，转发之后的请求对应的ip就是代理服务器的ip。</span><br></pre></td></tr></table></figure>

<p>3、提供免费代理ip的平台</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">www.goubanjia.com</span><br><span class="line">快代理</span><br><span class="line">西祠代理</span><br><span class="line">代理精灵:http://http.zhiliandaili.cn</span><br></pre></td></tr></table></figure>

<p>4 、代理ip的匿名度</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">透明：使用了透明的代理ip，则对方服务器知道你当前发起的请求使用了代理服务器并且可以监测到你真实的ip</span><br><span class="line">匿名：知道你使用了代理服务器不知道你的真实ip</span><br><span class="line">高匿：不知道你使用了代理服务器也不知道你的真实ip</span><br></pre></td></tr></table></figure>

<p>5、代理ip的类型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">http：该类型的代理IP只可以转发http协议的请求</span><br><span class="line">https：只可以转发https协议的请求</span><br></pre></td></tr></table></figure>

<p>6、作用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">尽可能多的将请求的IP设置成不同的</span><br></pre></td></tr></table></figure>

<p>7、操作流程</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1.在下载中间件中拦截请求</span><br><span class="line">2.将拦截到的请求的IP修改成某一代理IP</span><br><span class="line">3.在配置文件中开启下载中间件</span><br></pre></td></tr></table></figure>

<h2 id="二、案例分析"><a href="#二、案例分析" class="headerlink" title="二、案例分析"></a>二、案例分析</h2><h2 id="2-1、代理测试"><a href="#2-1、代理测试" class="headerlink" title="2.1、代理测试"></a>2.1、代理测试</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">headers =&#123;</span><br><span class="line"><span class="string">"User-Agent"</span>: <span class="string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36"</span></span><br><span class="line">&#125;</span><br><span class="line">url_pool = [</span><br><span class="line">    &#123;<span class="string">"https"</span>:<span class="string">"111.231.93.66:8888"</span>&#125;,</span><br><span class="line">    &#123;<span class="string">"https"</span>:<span class="string">"111.231.93.66:8888"</span>&#125;</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">url = <span class="string">"https://www.baidu.com/"</span></span><br><span class="line"></span><br><span class="line">content =requests.get(url=url,headers=headers,proxies=random.choice(url_pool)).text</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">"01"</span>,<span class="string">'w'</span>,encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> f:</span><br><span class="line">    f.write(content)</span><br></pre></td></tr></table></figure>

<h2 id="2-2构建一个标准的代理池"><a href="#2-2构建一个标准的代理池" class="headerlink" title="2.2构建一个标准的代理池"></a>2.2构建一个标准的代理池</h2><p>1、ua代理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>取各大平台中爬取大量的免费代理ip</span><br><span class="line"><span class="number">2.</span>校验出可用的代理ip</span><br><span class="line">使用每一个代理ip进行请求发送，监测响应状态码是否为<span class="number">200</span></span><br><span class="line"><span class="number">3.</span>将可用的代理ip进行存储（redis）</span><br></pre></td></tr></table></figure>

<p>2、代码实现</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、构建代理池</span></span><br><span class="line">all_ips = []</span><br><span class="line">ip_url = <span class="string">'http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&amp;packid=1&amp;fa=0&amp;fetch_key=&amp;groupid=0&amp;qty=53&amp;time=1&amp;pro=&amp;city=&amp;port=1&amp;format=html&amp;ss=5&amp;css=&amp;dt=1&amp;specialTxt=3&amp;specialJson='</span></span><br><span class="line">page_text = requests.get(ip_url,headers=headers).text</span><br><span class="line">tree = etree.HTML(page_text)</span><br><span class="line">ip_list = tree.xpath(<span class="string">'//body//text()'</span>)</span><br><span class="line"><span class="keyword">for</span> ip <span class="keyword">in</span> ip_list:</span><br><span class="line">    ip = &#123;<span class="string">'https'</span>:ip&#125;</span><br><span class="line">    all_ips.append(ip)</span><br><span class="line"><span class="comment">#1、构建代理池</span></span><br><span class="line">url = <span class="string">'https://www.xicidaili.com/nn/%d'</span></span><br><span class="line"><span class="keyword">for</span> page <span class="keyword">in</span> range(<span class="number">1</span>,<span class="number">100</span>):</span><br><span class="line">    print(<span class="string">'正在爬取第&#123;&#125;页的数据！'</span>.format(page))</span><br><span class="line">    new_url = format(url%page)</span><br><span class="line">    			     page_text=requests.get(url=new_url,headers=headers,proxies=random.choice(all_ips)).text</span><br><span class="line">    tree = etree.HTML(page_text)</span><br><span class="line">    tr_list = tree.xpath(<span class="string">'//*[@id="ip_list"]//tr'</span>)[<span class="number">1</span>:]</span><br><span class="line">    <span class="keyword">for</span> tr <span class="keyword">in</span> tr_list:</span><br><span class="line">        ip = tr.xpath(<span class="string">'./td[2]/text()'</span>)[<span class="number">0</span>]</span><br><span class="line">        port = tr.xpath(<span class="string">'./td[3]/text()'</span>)[<span class="number">0</span>]</span><br><span class="line">        ip_type = tr.xpath(<span class="string">'./td[6]/text()'</span>)[<span class="number">0</span>]</span><br><span class="line">        </span><br><span class="line">        dic = &#123;</span><br><span class="line">            <span class="string">'ip'</span>:ip,</span><br><span class="line">            <span class="string">'port'</span>:port,</span><br><span class="line">            <span class="string">'type'</span>:ip_type</span><br><span class="line">        &#125;</span><br><span class="line">        all_ips.append(dic)</span><br><span class="line">    </span><br><span class="line">print(len(all_ips))</span><br></pre></td></tr></table></figure>

<p>三、基于multiprocessing.dummy线程池的数据爬取</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br></pre></td><td class="code"><pre><span class="line">需求：爬取梨视频的视频信息，并计算其爬取数据的耗时</span><br><span class="line">普通爬取</span><br><span class="line">%%time</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">from</span> lxml <span class="keyword">import</span> etree</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> fake_useragent <span class="keyword">import</span> UserAgent</span><br><span class="line"><span class="comment">#安装fake-useragent库:pip install fake-useragent</span></span><br><span class="line">url = <span class="string">'http://www.pearvideo.com/category_1'</span></span><br><span class="line"><span class="comment">#随机产生UA,如果报错则可以添加如下参数：</span></span><br><span class="line"><span class="comment">#ua = UserAgent(verify_ssl=False,use_cache_server=False).random</span></span><br><span class="line"><span class="comment">#禁用服务器缓存：</span></span><br><span class="line"><span class="comment">#ua = UserAgent(use_cache_server=False)</span></span><br><span class="line"><span class="comment">#不缓存数据：</span></span><br><span class="line"><span class="comment">#ua = UserAgent(cache=False)</span></span><br><span class="line"><span class="comment">#忽略ssl验证：</span></span><br><span class="line"><span class="comment">#ua = UserAgent(verify_ssl=False)</span></span><br><span class="line"></span><br><span class="line">ua = UserAgent().random</span><br><span class="line">headers = &#123;</span><br><span class="line">    <span class="string">'User-Agent'</span>:ua</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">#获取首页页面数据</span></span><br><span class="line">page_text = requests.get(url=url,headers=headers).text</span><br><span class="line"><span class="comment">#对获取的首页页面数据中的相关视频详情链接进行解析</span></span><br><span class="line">tree = etree.HTML(page_text)</span><br><span class="line">li_list = tree.xpath(<span class="string">'//div[@id="listvideoList"]/ul/li'</span>)</span><br><span class="line">detail_urls = []</span><br><span class="line"><span class="keyword">for</span> li <span class="keyword">in</span> li_list:</span><br><span class="line">    detail_url = <span class="string">'http://www.pearvideo.com/'</span>+li.xpath(<span class="string">'./div/a/@href'</span>)[<span class="number">0</span>]</span><br><span class="line">    title = li.xpath(<span class="string">'.//div[@class="vervideo-title"]/text()'</span>)[<span class="number">0</span>]</span><br><span class="line">    detail_urls.append(detail_url)</span><br><span class="line"><span class="keyword">for</span> url <span class="keyword">in</span> detail_urls:</span><br><span class="line">    page_text = requests.get(url=url,headers=headers).text</span><br><span class="line">    vedio_url = re.findall(<span class="string">'srcUrl="(.*?)"'</span>,page_text,re.S)[<span class="number">0</span>]</span><br><span class="line">    </span><br><span class="line">    data = requests.get(url=vedio_url,headers=headers).content</span><br><span class="line">    fileName = str(random.randint(<span class="number">1</span>,<span class="number">10000</span>))+<span class="string">'.mp4'</span> <span class="comment">#随机生成视频文件名称</span></span><br><span class="line">    <span class="keyword">with</span> open(fileName,<span class="string">'wb'</span>) <span class="keyword">as</span> fp:</span><br><span class="line">        fp.write(data)</span><br><span class="line">        print(fileName+<span class="string">' is over'</span>)</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"></span><br><span class="line">基于线程池的爬取</span><br><span class="line">%%time</span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="keyword">from</span> lxml <span class="keyword">import</span> etree</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> fake_useragent <span class="keyword">import</span> UserAgent</span><br><span class="line"><span class="comment">#安装fake-useragent库:pip install fake-useragent</span></span><br><span class="line"><span class="comment">#导入线程池模块</span></span><br><span class="line"><span class="keyword">from</span> multiprocessing.dummy <span class="keyword">import</span> Pool</span><br><span class="line"><span class="comment">#实例化线程池对象</span></span><br><span class="line">pool = Pool()</span><br><span class="line">url = <span class="string">'http://www.pearvideo.com/category_1'</span></span><br><span class="line"><span class="comment">#随机产生UA</span></span><br><span class="line">ua = UserAgent().random</span><br><span class="line">headers = &#123;</span><br><span class="line">    <span class="string">'User-Agent'</span>:ua</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">#获取首页页面数据</span></span><br><span class="line">page_text = requests.get(url=url,headers=headers).text</span><br><span class="line"><span class="comment">#对获取的首页页面数据中的相关视频详情链接进行解析</span></span><br><span class="line">tree = etree.HTML(page_text)</span><br><span class="line">li_list = tree.xpath(<span class="string">'//div[@id="listvideoList"]/ul/li'</span>)</span><br><span class="line"></span><br><span class="line">detail_urls = []<span class="comment">#存储二级页面的url</span></span><br><span class="line"><span class="keyword">for</span> li <span class="keyword">in</span> li_list:</span><br><span class="line">    detail_url = <span class="string">'http://www.pearvideo.com/'</span>+li.xpath(<span class="string">'./div/a/@href'</span>)[<span class="number">0</span>]</span><br><span class="line">    title = li.xpath(<span class="string">'.//div[@class="vervideo-title"]/text()'</span>)[<span class="number">0</span>]</span><br><span class="line">    detail_urls.append(detail_url)</span><br><span class="line">    </span><br><span class="line">vedio_urls = []<span class="comment">#存储视频的url</span></span><br><span class="line"><span class="keyword">for</span> url <span class="keyword">in</span> detail_urls:</span><br><span class="line">    page_text = requests.get(url=url,headers=headers).text</span><br><span class="line">    vedio_url = re.findall(<span class="string">'srcUrl="(.*?)"'</span>,page_text,re.S)[<span class="number">0</span>]</span><br><span class="line">    vedio_urls.append(vedio_url) </span><br><span class="line"><span class="comment">#使用线程池进行视频数据下载    </span></span><br><span class="line">func_request = <span class="keyword">lambda</span> link:requests.get(url=link,headers=headers).content</span><br><span class="line">video_data_list = pool.map(func_request,vedio_urls)</span><br><span class="line"><span class="comment">#使用线程池进行视频数据保存</span></span><br><span class="line">func_saveData = <span class="keyword">lambda</span> data:save(data)</span><br><span class="line">pool.map(func_saveData,video_data_list)</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">save</span><span class="params">(data)</span>:</span></span><br><span class="line">    fileName = str(random.randint(<span class="number">1</span>,<span class="number">10000</span>))+<span class="string">'.mp4'</span></span><br><span class="line">    <span class="keyword">with</span> open(fileName,<span class="string">'wb'</span>) <span class="keyword">as</span> fp:</span><br><span class="line">        fp.write(data)</span><br><span class="line">        print(fileName+<span class="string">'已存储'</span>)</span><br><span class="line">        </span><br><span class="line">pool.close()</span><br><span class="line">pool.join()</span><br></pre></td></tr></table></figure>

<h2 id="二、UA池"><a href="#二、UA池" class="headerlink" title="二、UA池"></a>二、UA池</h2><p>1、作用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">尽可能多的将scrapy工程中的请求伪装成不同类型的浏览器身份。</span><br></pre></td></tr></table></figure>

<p>2、操作流程</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>在下载中间件中拦截请求</span><br><span class="line"><span class="number">2.</span>将拦截到的请求的请求头信息中的UA进行篡改伪装</span><br><span class="line"><span class="number">3.</span>在配置文件中开启下载中间件</span><br></pre></td></tr></table></figure>

<p>3、ua池</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">user_agent_list = [</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"</span>,</span><br><span class="line">        <span class="string">"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 "</span></span><br><span class="line">        <span class="string">"(KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>4、代码实现</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#导包</span></span><br><span class="line"><span class="keyword">from</span> scrapy.contrib.downloadermiddleware.useragent <span class="keyword">import</span> UserAgentMiddleware</span><br><span class="line"><span class="keyword">import</span> random</span><br><span class="line"><span class="comment">#UA池代码的编写（单独给UA池封装一个下载中间件的一个类）</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RandomUserAgent</span><span class="params">(UserAgentMiddleware)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">process_request</span><span class="params">(self, request, spider)</span>:</span></span><br><span class="line">        <span class="comment">#从列表中随机抽选出一个ua值</span></span><br><span class="line">        ua = random.choice(user_agent_list)</span><br><span class="line">        <span class="comment">#ua值进行当前拦截到请求的ua的写入操作</span></span><br><span class="line">        request.headers.setdefault(<span class="string">'User-Agent'</span>,ua</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/20/【爬虫02】1UA代理/" title="爬虫UA代理">http://yoursite.com/2019/09/20/【爬虫02】1UA代理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/爬虫/" rel="tag"># 爬虫</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/20/【爬虫02】0爬取数据常用模块 /" rel="next" title="爬虫常用模块一">
                <i class="fa fa-chevron-left"></i> 爬虫常用模块一
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/09/20/【爬虫03】03数据解析/" rel="prev" title="爬虫数据解析">
                爬虫数据解析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、代理池介绍"><span class="nav-number">1.</span> <span class="nav-text">一、代理池介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、案例分析"><span class="nav-number">2.</span> <span class="nav-text">二、案例分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1、代理测试"><span class="nav-number">3.</span> <span class="nav-text">2.1、代理测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2构建一个标准的代理池"><span class="nav-number">4.</span> <span class="nav-text">2.2构建一个标准的代理池</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、UA池"><span class="nav-number">5.</span> <span class="nav-text">二、UA池</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
